package com.wxh.multithread;

/**
 * @ClassName: TestThreadLocal
 * @Description: 测试线程本地存储：数据隔离，线程中数据私有化
 * @Author wxh
 * @Date: 2022/1/7 15:44
 * @Version V1.0.0
 * @Since 1.8
 */
public class TestThreadLocal {


    /**
     * 可以看出每个线程，对应的值是一致的
     * @param args
     */
    public static void main(String[] args) {
        final A a = new A();
        final B b = new B();
        for (int i = 0; i < 15; i++) {
            final String resource1 = "线程-" + i;
            final String resource2 = "value = (" + i + ")";
            new Thread(() -> {
                try {
                    a.setOne(resource1);
                    a.setTwo(resource2);
                    b.display();
                }finally {
                    // 防止内存泄露
                    ResourceClass.RESOURCE_ONE.remove();
                    ResourceClass.RESOURCE_TWO.remove();
                }
            }).start();
        }
    }


    /**
     * 静态内部类
     */
    static class ResourceClass {
        /**
         * 定义了两个ThreadLocal变量
         */
        public static final ThreadLocal<String> RESOURCE_ONE = new ThreadLocal<>();
        public static final ThreadLocal<String> RESOURCE_TWO = new ThreadLocal<>();
    }

    static class A{
        public void setOne(String value){
            ResourceClass.RESOURCE_ONE.set(value);
        }
        public void setTwo(String value){
            ResourceClass.RESOURCE_TWO.set(value);
        }
    }
    static class B{
        public void display(){
            System.out.println(ResourceClass.RESOURCE_ONE.get() + ": " + ResourceClass.RESOURCE_TWO.get());
        }
    }
}
